package com.example.petproject.controller;

import com.example.petproject.constants.Constants;
import com.example.petproject.entity.model.UmsUser;
import com.example.petproject.entity.vo.CartProductVO;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.entity.vo.ReturnVO;
import com.example.petproject.execption.BaseException;
import com.example.petproject.service.OmsCartService;
import com.example.petproject.service.impl.OmsCartServiceImpl;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.PetUmsUtils;
import com.example.petproject.util.RedisKeyUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名称：com.example.petproject.controller
 * 类名称：OmsCartController
 * 类描述：购物车控制器
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月17日 15:23
 **/
@RestController
@RequestMapping("/oms/cart")
public class OmsCartController {

    private static final Logger log = LoggerFactory.getLogger(OmsCartController.class);
    @Resource
    private OmsCartService omsCartService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/add")
    public ReturnVO<Void> addCart(Long skuId, Integer num, @RequestHeader(value = "Token", required = false) String token) {
        if (ObjectUtils.isEmpty(token)) {
            log.warn("token为空，当前用户未登录");
            return ReturnVO.error(ReturnStatusEnum.AUTH_TOKEN_EMPTY);
        }
        //先根据token获取用户信息
        String tokenKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_TOKEN, token);
        String loginUserStr = stringRedisTemplate.opsForValue().get(tokenKey);
        if (!StringUtils.hasText(loginUserStr)) {
            log.warn("当前用户未登录，或者token已失效");
            return ReturnVO.error(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
        }
        //将用户信息反序列化,获取用户id
        try {
            UmsUser umsUser = ObjectMapperUtils.stringToObj(loginUserStr, UmsUser.class);
            Long userId = umsUser.getId();
            Boolean result = omsCartService.addCart(skuId, num, userId);
            return result ? ReturnVO.ok() : ReturnVO.error();
        } catch (JsonProcessingException e) {
            log.error("添加购物车异常：{}", e.getMessage());
            return ReturnVO.error();
        }

    }


    @GetMapping("/cartCount")
    public ReturnVO<?> cartCount(@RequestHeader(value = "Token", required = false) String token) {
        //先从redis中取出用户信息
        String loginUserKey = PetUmsUtils.generateTokenRedisKey(token);
        String loginUserStr = stringRedisTemplate.opsForValue().get(loginUserKey);
        if (!StringUtils.hasText(loginUserStr)) {
            return ReturnVO.error(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
        }
        //反序列化当前用户
        try {
            UmsUser loginUser = ObjectMapperUtils.stringToObj(loginUserStr, UmsUser.class);
            //根据当前用户Id生成购物车对应的redis key
            String cartKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_CART, String.valueOf(loginUser.getId()));
            //所有商品映射关系
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(cartKey);
            Integer cartCount = ObjectUtils.isEmpty(entries) ? 0 : entries.size();
            Map<String, Integer> cartCountMap = new HashMap<>();
            cartCountMap.put("cartCount",cartCount);
            return ReturnVO.ok(cartCountMap);
        } catch (JsonProcessingException e) {
            log.error("反序列化异常：", e);
            return ReturnVO.error(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }

    @GetMapping("/cartList")
    public ReturnVO<?> cartList(@RequestHeader(value = "Token", required = false) String token) {
        //先从redis中取出用户信息
        String loginUserKey = PetUmsUtils.generateTokenRedisKey(token);
        String loginUserStr = stringRedisTemplate.opsForValue().get(loginUserKey);
        if (!StringUtils.hasText(loginUserStr)) {
            return ReturnVO.error(ReturnStatusEnum.AUTH_USER_NOT_LOGIN);
        }
        //反序列化当前用户
        try {
            UmsUser loginUser = ObjectMapperUtils.stringToObj(loginUserStr, UmsUser.class);
            //根据当前用户Id生成购物车对应的redis key
            List<CartProductVO> cartList = omsCartService.getCartList(loginUser.getId());
            return ReturnVO.ok(cartList);
        } catch (JsonProcessingException e) {
            log.error("反序列化异常：", e);
            return ReturnVO.error(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }


}
